<template>
  <el-card class="sku-card">
    <el-form
      label-width="100px"
      :model="skuFormData"
      :rules="rules"
      ref="skuFormRef"
    >
      <el-form-item label="SPU名称">
        <span>{{ spu.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input
          placeholder="请输入SKU名称"
          v-model="skuFormData.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="请输入规格描述"
          type="textarea"
          :rows="2"
          v-model="skuFormData.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="sku-row">
          <el-col
            :sm="24"
            :md="12"
            :lg="8"
            :xl="6"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <div class="sku-wrap">
              <span class="sku-name">{{ attr.attrName }}</span>
              <el-select
                v-if="skuFormData.skuAttrValueList"
                class="sku-select"
                v-model="skuFormData.skuAttrValueList[index]"
              >
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" v-if="spuSaleAttrList">
        <el-row :gutter="10" class="sku-row">
          <el-col
            :sm="24"
            :md="12"
            :lg="8"
            :xl="6"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <div class="sku-wrap">
              <span class="sku-name">{{ saleAttr.saleAttrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormData.skuSaleAttrValueList[index]"
              >
                <!-- 
                将来发送请求添加Sku，携带平台属性数据，需要4个参数 
              -->
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="success"
                size="small"
                disabled
                v-if="row.isDefault === '1'"
                >默认图片</el-button
              >
              <!-- 请求回来的数据没isDefault, 或isDefault为0 -->
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setDefaultImg(row)"
                >设置默认图片</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="emit('setIsShow', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveSku",
};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue";
import { useCategoryStore } from "@/stores/category";
import { getAttrListApi } from "@/api/product/attr";
import { getSpuSaleAttrListApi, getSpuImageListApi } from "@/api/product/spu";
import type { SpuItem, SpuSaleAttrList } from "@/api/product/model/spuModel";
import type { AttrList } from "@/api/product/model/attrModel";
import type {
  SaveSkuItem,
  SkuImageList,
  SkuImageItem,
} from "@/api/product/model/skuModel";
import { ElMessage } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
import { saveSkuApi } from "@/api/product/sku";

const props = defineProps<{
  spu: SpuItem;
}>();

const emit = defineEmits(["setIsShow"]);

// 定义数据
const attrList = ref<AttrList>([]); // 平台属性列表
const spuSaleAttrList = ref<SpuSaleAttrList>([]); // 销售属性列表
const spuImageList = ref<SkuImageList>([]); // 图片列表

const categoryStore = useCategoryStore();

onMounted(async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
});

onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(props.spu.id as number);
});

onMounted(async () => {
  const imageList = await getSpuImageListApi(props.spu.id as number);
  spuImageList.value = imageList.map((img) => {
    return {
      ...img,
      isDefault: "0",
    };
  });
});

// 定义表单数据
const skuFormData = reactive<SaveSkuItem>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  // 平台属性列表
  skuAttrValueList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 默认图片
  skuDefaultImg: "",
});

const skuImageListValidator = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback(new Error("至少选中一张图片"));
    return;
  }

  if (value.some((img: SkuImageItem) => img.isDefault === "1")) {
    callback();
    return;
  }

  callback(new Error("至少选中默认图片"));
};

// 定义表单校验规则
const rules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入Sku名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入Sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入Sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入Sku规格描述", trigger: "blur" }],
  // 平台属性列表
  skuAttrValueList: [
    { required: true, message: "请选择平台属性", trigger: "change" },
  ],
  // 销售属性列表
  skuSaleAttrValueList: [
    { required: true, message: "请选择销售属性", trigger: "change" },
  ],
  // 图片列表
  skuImageList: [
    { required: true, validator: skuImageListValidator, trigger: "change" },
  ],
});

// table复选框变化触发的回调函数
const handleSelectionChange = (val: SkuImageList) => {
  skuFormData.skuImageList = val;
};

// 设置默认图片
const setDefaultImg = (row: SkuImageItem) => {
  spuImageList.value.forEach((img: SkuImageItem) => (img.isDefault = "0"));
  // 将当前图片设置为默认
  row.isDefault = "1";
  skuFormData.skuDefaultImg = row.imgUrl;
  // 清空校验结果
  skuFormRef.value?.clearValidate(["skuImageList"]);
};

const skuFormRef = ref<FormInstance>();

const submitForm = () => {
  skuFormRef.value?.validate(async (valid) => {
    if (valid) {
      const { skuAttrValueList, skuSaleAttrValueList, ...rest } = skuFormData;
      // 成功
      await saveSkuApi({
        ...rest,
        skuAttrValueList: skuFormData.skuAttrValueList
          .filter(Boolean)
          .map((attr) => {
            const [attrId, attrName, valueId, valueName] = attr.split(":");
            return {
              attrId: +attrId,
              attrName,
              valueId: +valueId,
              valueName,
            };
          }),
        skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
          .filter(Boolean)
          .map((saleAttr) => {
            const [
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            ] = saleAttr.split(":");
            return {
              saleAttrId: +saleAttrId,
              saleAttrName,
              saleAttrValueId: +saleAttrValueId,
              saleAttrValueName,
            };
          }),
        spuId: props.spu.id as number,
        category3Id: categoryStore.category3Id as number,
      });

      ElMessage.success("添加Sku成功");
      emit("setIsShow", 1);
    }
  });
};
</script>

<style lang="scss" scoped>
.sku-card {
  margin-top: 20px;
}

.sku-input-number {
  width: 100%;
}

.sku-select {
  margin-bottom: 10px;
}

.sku-wrap {
  display: flex;
  justify-content: space-between;
}

.sku-name {
  font-weight: 500;
}

.sku-img {
  width: 150px;
  height: 100px;
}

.sku-row {
  width: 100%;
}
</style>

<style>
.sku-input-number .el-input__inner {
  text-align: left;
}
</style>
